package com.taotao.search.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.taotao.common.SearchResult;
import com.taotao.search.service.SearchItemService;
import com.taotao.search.service.SearchService;

/**
 * 通过用户 输入的查询条件查询 索引库返回数据到 页面  实现 搜索的controller
 * @author created by wq
 * @date   Sep 1, 2017---4:06:49 PM
 * @return
 * @throws Exception<br/>
 *==========History========== <br/>
 * taotao-search-web Sep 1, 2017
 */
@Controller
public class SearchItemController {

	@Value("${PAGESIZE}")
	private Integer PAGESIZE;
	
	@Autowired
	private SearchService searchService;
	/**
	 * 根据查询条件queryString 查询索引库查询数据
	 * [http://localhost:8085/search.html?q="+SEARCH.query+"&page="+b;]
	 * 前端传过来的参数有： queryString , page=b(默认为1),pageSize =在配置文件中设置读取
	 */
	@RequestMapping("/search")
	public String searchItemByQuery(@RequestParam("q") String queryString,
			@RequestParam(defaultValue="1")Integer page,Model model) throws Exception{
		
		//处理请求参数乱码问题
		queryString = new String(queryString.getBytes("iso8859-1"), "utf-8");
		//调用业务层
		SearchResult searchResult = searchService.searchItemByQuery(queryString, page, PAGESIZE);
		
		//将业务层返回来的数据添加到model中，然后通过视图解析器去对search.jsp进行数据渲染【传递到视图】
		model.addAttribute("itemList", searchResult.getItemList());
		model.addAttribute("totalPages", searchResult.getPageCount());
		model.addAttribute("page", page);
		model.addAttribute("query", queryString);
//		int a =1/0;
		//返回逻辑视图
		
		return "search";
		
	}
}
